/*
 * This file is part of Movie Browser.
 * 
 * Copyright (C) Francis De Brabandere
 * 
 * Movie Browser is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * Movie Browser is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package eu.somatik.moviebrowser.gui;

import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;

import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flicklib.api.MovieInfoFetcher;
import com.flicklib.domain.MovieSearchResult;
import com.flicklib.domain.MovieService;

import eu.somatik.moviebrowser.domain.MovieInfo;
import eu.somatik.moviebrowser.service.MovieFinder;

/**
 *
 * @author  rug
 */
public class EditMovieFrame extends javax.swing.JFrame {

    private static final Logger LOGGER = LoggerFactory.getLogger(EditMovieFrame.class);
    private final MovieInfoFetcher fetcher;
    private final DefaultListModel listModel;
    private final MovieInfo movieInfo;
    private final MovieFinder movieFinder;
    private final MovieService service;
    private final ResourceBundle bundle;
    /** 
     * Creates new form EditMovieFrame
     * @param movieInfo 
     * @param fetcher 
     * @param movieFinder
     */
    public EditMovieFrame(MovieInfo movieInfo, MovieInfoFetcher fetcher, MovieService service, MovieFinder movieFinder) {
        this.fetcher = fetcher;
        this.movieFinder = movieFinder;
        this.movieInfo = movieInfo;
        this.service = service;
        this.bundle = ResourceBundle.getBundle("eu/somatik/moviebrowser/gui/Bundle"); // NOI18N
        

        this.listModel = new DefaultListModel();
        initComponents();
        searchTextField.setText(movieInfo.getMovie().getTitle());
        resultsList.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    resultsListDoubleClick();
                }
            }
        });
        resultsList.setCellRenderer(new MovieListCellRenderer());

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchTextField = new javax.swing.JTextField();
        searchLabel = new javax.swing.JLabel();
        searchButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        resultsList = new javax.swing.JList();
        updateButton = new javax.swing.JButton();
        statusProgressBar = new javax.swing.JProgressBar();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("eu/somatik/moviebrowser/gui/Bundle"); // NOI18N
        setTitle(bundle.getString("EditMovieFrame.title")); // NOI18N
        setIconImage(new ImageIcon(EditMovieFrame.getFrames().getClass().getResource("/images/movie.png")).getImage());

        searchTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchTextFieldActionPerformed(evt);
            }
        });

        searchLabel.setText(bundle.getString("EditMovieFrame.searchLabel.text")); // NOI18N

        searchButton.setText(bundle.getString("EditMovieFrame.searchButton.text")); // NOI18N
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        resultsList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        resultsList.setToolTipText(bundle.getString("EditMovieFrame.resultsList.toolTipText")); // NOI18N
        resultsList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                resultsListMouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                resultsListMouseReleased(evt);
            }
        });
        resultsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                resultsListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(resultsList);

        updateButton.setText(bundle.getString("EditMovieFrame.updateButton.text")); // NOI18N
        updateButton.setToolTipText(bundle.getString("EditMovieFrame.updateButton.toolTipText")); // NOI18N
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });

        statusProgressBar.setForeground(new java.awt.Color(255, 153, 51));
        statusProgressBar.setString(bundle.getString("EditMovieFrame.statusProgressBar.string")); // NOI18N
        statusProgressBar.setStringPainted(true);

        cancelButton.setText(bundle.getString("EditMovieFrame.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(searchLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(searchTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusProgressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(updateButton)
                .addContainerGap())
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchButton)
                    .addComponent(searchLabel)
                    .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(updateButton)
                    .addComponent(statusProgressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
    statusProgressBar.setIndeterminate(true);
    statusProgressBar.setString(bundle.getString("EditMovieFrame.searchInProgress"));// NOI18N

    SwingWorker<List<? extends MovieSearchResult>, Void> worker =
            new SwingWorker<List<? extends MovieSearchResult>, Void>() {

                @Override
                public List<? extends MovieSearchResult> doInBackground() throws Exception {
                    return fetcher.search(searchTextField.getText().trim());
                }

                @Override
                public void done() {
                    try {
                        showResults(get());
                    } catch (InterruptedException ex) {
                        LOGGER.error("Get request intterrupted: ", ex);
                        statusProgressBar.setIndeterminate(false);
                        statusProgressBar.setString("Error Retrieving Results");
                    } catch (ExecutionException ex) {
                        LOGGER.error("Get request failed: ", ex.getCause());
                        statusProgressBar.setIndeterminate(false);
                        statusProgressBar.setString("Error Retrieving Results");
                    }
                }
            };
    worker.execute();
}//GEN-LAST:event_searchButtonActionPerformed

private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
    MovieSearchResult moviePage = (MovieSearchResult) resultsList.getSelectedValue();
    if (moviePage == null) {
        JOptionPane.showMessageDialog(EditMovieFrame.this, java.util.ResourceBundle.getBundle("eu/somatik/moviebrowser/gui/Bundle").getString("EditMovieFrame.noMovieSelected"));
    } else {
        movieInfo.getMovie().setTitle(moviePage.getPreferredTitle());
        movieInfo.getMovie().getMovieSiteInfoOrCreate(service).setIdForSite(moviePage.getIdForSite());
        movieInfo.setLoadType(MovieInfo.LoadType.TITLE_CHANGED);
        movieInfo.setNeedRefetch(true);
        movieFinder.reloadMovie(movieInfo);
        this.dispose();
    }

}//GEN-LAST:event_updateButtonActionPerformed

private void resultsListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultsListMouseClicked
}//GEN-LAST:event_resultsListMouseClicked

private void resultsListMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resultsListMouseReleased
}//GEN-LAST:event_resultsListMouseReleased

private void resultsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_resultsListValueChanged
    MovieSearchResult moviePage = (MovieSearchResult) resultsList.getSelectedValue();   
    if(moviePage != null){
        /*String tooltip = "You have selected " + moviePage.getTitle();
        resultsList.setToolTipText(tooltip + ". Double click selection to go to the IMDB page or click Update button to update.");
        updateButton.setToolTipText(tooltip + ". Click here to update.");*/
        resultsList.setToolTipText(MessageFormat.format(
                bundle.getString("EditMovieFrame.resultList.movie_tooltip"), moviePage.getTitle()));
        updateButton.setToolTipText(MessageFormat.format(
                bundle.getString("EditMovieFrame.updateButton.movie_tooltip"), moviePage.getTitle()));
        
        
    }
}//GEN-LAST:event_resultsListValueChanged

private void searchTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchTextFieldActionPerformed
    searchButtonActionPerformed(evt);
}//GEN-LAST:event_searchTextFieldActionPerformed

private void cancelPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelPerformed
// TODO add your handling code here:
    this.dispose();
}//GEN-LAST:event_cancelPerformed

private void resultsListDoubleClick() {
    MovieSearchResult moviePage = (MovieSearchResult) resultsList.getSelectedValue();
    String url = moviePage.getUrl();
    try {
        Desktop.getDesktop().browse(new URI(url));
    } catch (URISyntaxException ex) {
        LOGGER.error("Failed launching default browser for " + url, ex);
    } catch (IOException ex) {
        LOGGER.error("Failed launching default browser for " + url, ex);
    }   
}    

 
 private void showResults(List<? extends MovieSearchResult> movies){
     
        listModel.clear();
        for(MovieSearchResult movie : movies){
            listModel.addElement(movie);
        }
        
        resultsList.setModel(listModel);
        statusProgressBar.setIndeterminate(false);
        if(listModel.isEmpty()) {
            statusProgressBar.setString(bundle.getString("EditMovieFrame.noResultsFound"));
        } else {
            statusProgressBar.setString(MessageFormat.format(bundle.getString("EditMovieFrame.resultsFound"),
                    listModel.getSize()));
        }
 }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JList resultsList;
    private javax.swing.JButton searchButton;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JTextField searchTextField;
    private javax.swing.JProgressBar statusProgressBar;
    private javax.swing.JButton updateButton;
    // End of variables declaration//GEN-END:variables



}
